/*****************************************************************************************
**  Author:jxx 2022
**  QQ:283591387
**完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
**常用示例见：http://v2.volcore.xyz/document/vueDev
**后台操作见：http://v2.volcore.xyz/document/netCoreDev
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import { effect } from 'vue';
import gridHeader   from './EQU_COM_DEFINITION_TASKHead.vue'; 
import gridBody   from './EQU_COM_DEFINITION_TASKBody.vue';
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: gridHeader,
    gridBody: gridBody,
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮


  data() {
    return {
      message: "等待接收消息...",
      msgs: [],
      dataInfo: {
        status1: "off",
        status2: "off"
      },
      pushContent: "",
      connection: null,
      isConnected: false,
      connectionError: null,
      reconnectAttempts: 0,
      signalRUrl: CHAT_HUB_URL,
      maxReconnectAttempts: 5
    };
  },
  methods: {
  
    mounted() {

      this.$nextTick(() => {
        console.log('DOM更新后立即执行');
     
       // this.$refs.gridBody.setErrorMessage();
        this.$refs.gridHeader.model1 = false;
        // 如果需要延迟执行，可以继续使用setTimeout或Promise方法

   
      });
      // 每3秒刷新一次页面
      this.timer = setInterval(() => {
        this.onRefresh();
    
      //  window.location.reload();
      }, 30000);
    },
    beforeDestroy() {
    
      // 清除定时器，避免页面销毁时定时器还在运行
      clearInterval(this.timer);
    },
    onRefresh() { 
      this.refresh();},
     //下面这些方法可以保留也可以删除
    onInit() {  //框架初始化配置前，
        //示例：在按钮的最前面添加一个按钮
          // this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
          //   name: '自动刷新', //按钮名称
          //   disabled: true, //按钮是否禁用
          //   icon: 'el-icon-refresh', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
          //   type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
          //   onClick: function () {
          //     //this.$Message.success('点击了按钮');
          //     this.mounted();
          //   }
          // });
          this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
            name: '消息', //按钮名称
          //  icon: 'el-icon-video-pause', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
          icon: 'el-icon-refresh',
            type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
            onClick: function () {
              
              this.$refs.gridBody.setErrorMessage();
              this.$refs.gridBody.messages3=[];
       
            }
          });
          this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
            name: '停止刷新', //按钮名称
          //  icon: 'el-icon-video-pause', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
          icon: 'el-icon-refresh',
            type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
            onClick: function () {
            // this.boxButtons[0].readonly=true;
            // this.boxButtons[1].disabled =true;
           // x.hidden=true;
            //this.boxButtons[1].hidden =true;
              this.$Message.success(this.buttons[0].name);
              if(this.buttons[0].name=="停止刷新"){
                this.beforeDestroy();
                this.buttons[0].name="自动刷新";
           this.   beforeDestroy();
            }
            else{
              this.buttons[0].name="停止刷新";
              this.mounted();
            }
            }
          });

        //示例：设置修改新建、编辑弹出框字段标签的长度
        // this.boxOptions.labelWidth = 150;

        // if (x.field == "Variety") {
           //设置table有数据源的列为正常显示(不显示背景颜色)
        //   x.normal = true;
        // }
   
        this.columns.forEach(x => {
          if (x.field == 'ExecuteTaskDiffTime') {
            x.formatter = (row) => {
              if(row.ExecuteTaskDiffTime>0){
              
               
                 return ''+this.secondsToTime(row.ExecuteTaskDiffTime)+'(预估'+row.time+')'
                // return '<span style="color: #ff0000;">'+this.secondsToTime(row.ExecuteTaskDiffTime)+'</span>'
              }else if(row.ExecuteStart!=null)
              { 
                var currentDate = new Date();
                let dateObject = new Date(row.ExecuteStart);
                return ''+this.secondsToTime(row.ExecuteTaskDiffTime)+'(预估'+row.time+')'+'(截止'+this.calculateTimeDifference(dateObject,currentDate)+')'}
                else{
                if(row.ProgramId!=''){
                  return '(预估'+row.time+')'}
                 return ''
               //  return '<span style="color: #2d8cf0;">'+row.ExecuteTaskDiffTime+'</span>'
              }
             
            }
          }
          if (x.field=='TaskNo') {
            x.formatter = (row) => {
              var lockstr='<a href="/#/V_PLAN_WORK_ORDER_Action?OrderCode='+row.OrderCode+'" target="_self"><div style="color:red;font-weight: bold" class="input-icon el-icon-lock"></div></a>';
              if(row.IsActivation=="1"){
                lockstr='<a href="/#/V_PLAN_WORK_ORDER_Action?OrderCode='+row.OrderCode+'" target="_self"><div style="color:green;font-weight: bold" class="input-icon el-icon-unlock"></div></a>';
              }else if(row.IsActivation=="0"){
                lockstr='<a href="/#/V_PLAN_WORK_ORDER_Action?OrderCode='+row.OrderCode+'" target="_self"><div  style="color:red;font-weight: bold" class="input-icon el-icon-lock"></div></a>';
              }
              if(row.Command=="TW004"||row.Command=="TW0041"){
                var arr=row.TaskNo.split("-");
                return ''+lockstr+' <span style="color: red;font-weight: bold;">【'+arr[arr.length-1]+'】</span>'+row.TaskNo+''
              }else{
               
                // return `<a href="javascript:void(0);" @click="test">11点击我</a><span onclick="test()">点击我</span>`;
                //添加事件
               return ' '+lockstr+' '+row.TaskNo+''
              }
            }
            
            x.fixed=true//也可以设置为right,固定到最右边
        }
        if(x.field=='Command'){
          //Command
          x.formatter = (row) => {
            if(row.Command=="TW004"||row.Command=="TW0041"){
              var arr=row.TaskNo.split("-");
              return '<span style="color: red;font-weight: bold;">【'+arr[arr.length-1]+'】</span>'+row.Command+''
            }else{
              return ''+row.Command+''
            }
        }
        }
            x.normal = true;
            x.cellStyle = (row, rowIndex, columnIndex) => {           
                if(row.Status=="3"){
                  return { background: "#33cc99", color: "#ffff" }
                }
                else if(row.Status=="2")//执行中
                {
                  return { background: "#cc9933", color: "#ffff" }
                }else if(row.Status=="5")//重做
                {
                  return { background: "#f56c6c", color: "#ffff" }
                }else if(row.Status=="4")//异常
                {                  
                  return { background: "#ff9933", color: "#ffff" }
                }else if(row.Status=="6")
                {
                  return{background:"#999999",color:"#ffff"}
                }
                else{
                 // return { background: "#33cc99", color: "#ffff" }
                } 
            }
          // }
          })
        this.textInline = false;
        this.columns.push({
          field: '操作',
          title: '操作',
          width: 150,
          fixed: 'right',
          align: 'center',
          render: (h, { row, column, index }) => {
            
            if( (row.Status=="1"||row.Status=='4'||row.Status=='5')&& row.ActionSort!=1){
              if(row.Status=="4"){

                return h('div', { style: { color: '#0e84ff' } }, [
                  h(
             
                    <el-tooltip class="item" effect="light" content="弃用" placement="top-start">
                 <span style="color:#E6A23C; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
                 onClick={($e) => {
                  let tigger = false;
                  this.$confirm(
                    "确认要弃用【"+row.TaskNo+"】吗？",
                    "警告",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                      center: true,
                    }
                  ).then(() => {
                    if (tigger) return;
                    tigger = true;
                    row.Status=6;// "6";//弃用
                    this.request('taskreceive', row);
  
                  }); 
                }}
                 > <i class="el-icon-scissors"></i></span>
                       
                  </el-tooltip>,        
                   
                ),
                  // h(
                  //   'span',
                  //   {
                  //     style: {
                  //       cursor: 'pointer',
                  //       'margin-right': '8px',
                  //       'border-bottom': '1px solid'
                  //     },
                  //     onClick: (e) => {
                  //       let tigger = false;
                  //     this.$confirm(
                  //       "确认要继续加工【"+row.TaskNo+"】吗？",
                  //       "警告",
                  //       {
                  //         confirmButtonText: "确定",
                  //         cancelButtonText: "取消",
                  //         type: "warning",
                  //         center: true,
                  //       }
                  //     ).then(() => {
                  //       if (tigger) return;
                  //       tigger = true;
                  //     //  row.Status=5;//继续加工
                  //       this.request('taskcontinue', row);

                  //     });
                  //     }
                  //   },
                  //   '继续加工'
                  // ),
                  h(
             
                    <el-tooltip class="item" effect="light" content="继续加工" placement="top-start">
                 <span style="color:green; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
                 onClick={($e) => {
                  let tigger = false;
                  this.$confirm(
                    "确认要继续加工【"+row.TaskNo+"】吗？",
                    "警告",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                      center: true,
                    }
                  ).then(() => {
                    if (tigger) return;
                    tigger = true;
                    this.request('taskcontinue', row);

                  });
                }}
                 > <i class="el-icon-info"> 继续</i></span>
                       
                  </el-tooltip>,        
                   
                ),
                  // h(
                  //   'span',
                  //   {
                  //     style: {
                  //       cursor: 'pointer',
                  //       'margin-right': '8px',
                  //       'border-bottom': '1px solid'
                  //     },
                  //     onClick: (e) => {
                  //       let tigger = false;
                  //       this.$confirm(
                  //         "确认要再次执行【"+row.TaskNo+"】吗？",
                  //         "警告",
                  //         {
                  //           confirmButtonText: "确定",
                  //           cancelButtonText: "取消",
                  //           type: "warning",
                  //           center: true,
                  //         }
                  //       ).then(() => {
                  //         if (tigger) return;
                  //         tigger = true;
                  //         row.Status=5;//重做
                  //         this.request('taskExecuteAgain', row);
  
                  //       });
  
                  //     }
                  //   },
                  //   '再次执行'
                  // ),
                  h(
             
                    <el-tooltip class="item" effect="light" content="再次执行" placement="top-start">
                 <span style=" cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
                 onClick={($e) => {
                  let tigger = false;
                  this.$confirm(
                    "确认要再次执行【"+row.TaskNo+"】吗？",
                    "警告",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                      center: true,
                    }
                  ).then(() => {
                    if (tigger) return;
                    tigger = true;
                    row.Status=5;//重做
                    this.request('taskExecuteAgain', row);
  
                  });
                }}
                 > <i class="el-icon-info">再次 </i></span>
                       
                  </el-tooltip>,        
                   
                ),
                h(
             
                  <el-tooltip class="item" effect="light" content="显示异常" placement="top-start">
               <span style="color:#E6A23C; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                this.$refs.gridHeader.openModel3(row, column, index);   
              }}
               > <i class="el-icon-warning">异常</i></span>
                     
                </el-tooltip>,        
                 
              ),
                  
              
                ]);
                

              }
              else{
              return h('div', { style: { color: '#0e84ff' } }, [
                h(
             
                  <el-tooltip class="item" effect="light" content="弃用" placement="top-start">
               <span style="color:#E6A23C; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                let tigger = false;
                this.$confirm(
                  "确认要弃用【"+row.TaskNo+"】吗？",
                  "警告",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    center: true,
                  }
                ).then(() => {
                  if (tigger) return;
                  tigger = true;
                  row.Status=6;// "6";//弃用
                  this.request('taskreceive', row);

                }); 
              }}
               > <i class="el-icon-scissors"></i></span>
                     
                </el-tooltip>,        
                 
              ),
                
            
              ]);
            }
            }else{

                //重新生成
            if(row.ActionSort==1){
              return h('div', { style: { color: '#0e84ff' } }, [
  
                h(
             
                    <el-tooltip class="item" effect="light" content="生成" placement="top-start">
                 <span style="color:green; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
                 onClick={($e) => {
                  let tigger = false;
                  this.$confirm(
                    "确认要生成【"+row.OrderCode+"】新版本吗？",
                    "警告",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                      center: true,
                    }
                  ).then(() => {
                    if (tigger) return;
                    tigger = true;
                    this.request('taskgenerate', row);
          
                  });
                }}
                 > <i class="el-icon-video-play">生成</i> </span>
                       
                  </el-tooltip>,        
                   
                ),
                h(
             
                  <el-tooltip class="item" effect="light" content="显示预警" placement="top-start">
               <span style="color:green; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                this.$refs.gridHeader.openModel1(row, column, index);  
              }}
               > <i class="el-icon-info"> 预警</i></span>
                     
                </el-tooltip>,        
                 
              ),
                // h(
                //   'span',
                //   {
                //     class:"el-icon-info",
                //     style: {
                //       cursor: 'pointer',
                //       'margin-right': '8px',
                //       'border-bottom': '1px solid'
                //     },
                //     onClick: (e) => {
                //      this.$refs.gridHeader.openModel1(row, column, index);  
               
                //     }
                //   },
                //   '显示预警'
                // )
            
              ]);
            }else{
              if(row.Status=="6"){
                return h('div', { style: { color: '#0e84ff' } }, [
                  h(
             
                    <el-tooltip class="item" effect="light" content="显示Log" placement="top-start">
                 <span style=" cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
                 onClick={($e) => {
                  this.$refs.gridHeader.openModel2(row, column, index);
                }}
                 > <i class="el-icon-view"></i></span>
                       
                  </el-tooltip>,        
                   
                ),
                  h(
             
                    <el-tooltip class="item" effect="light" content="再次执行" placement="top-start">
                 <span style=" cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
                 onClick={($e) => {
                  let tigger = false;
                  this.$confirm(
                    "确认要再次执行【"+row.TaskNo+"】吗？",
                    "警告",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                      center: true,
                    }
                  ).then(() => {
                    if (tigger) return;
                    tigger = true;
                    row.Status=5;//重做
                    this.request('taskExecuteAgain', row);
  
                  });
                }}
                 > <i class="el-icon-info">再次 </i></span>
                       
                  </el-tooltip>,        
                   
                ),
                  
                h(
             
                  <el-tooltip class="item" effect="light" content="显示异常" placement="top-start">
               <span style="color:#E6A23C; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                this.$refs.gridHeader.openModel3(row, column, index);   
              }}
               > <i class="el-icon-warning">异常</i></span>
                     
                </el-tooltip>,        
                 
              ),
              
                ]);
              }
              if(row.Status=="3"||row.Status=="2"){
              return h('div', { style: { color: '#0e84ff' } }, [
                h(
             
                  <el-tooltip class="item" effect="light" content="弃用" placement="top-start">
               <span style="color:#E6A23C; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                let tigger = false;
                this.$confirm(
                  "确认要弃用【"+row.TaskNo+"】吗？",
                  "警告",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    center: true,
                  }
                ).then(() => {
                  if (tigger) return;
                  tigger = true;
                  row.Status=6;// "6";//弃用
                  this.request('taskreceive', row);

                }); 
              }}
               > <i class="el-icon-scissors"></i></span>
                     
                </el-tooltip>,        
                 
              ),
               
                h(
             
                  <el-tooltip class="item" effect="light" content="显示Log" placement="top-start">
               <span style=" cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                this.$refs.gridHeader.openModel2(row, column, index);
              }}
               > <i class="el-icon-view"></i></span>
                     
                </el-tooltip>,        
                 
              ),
                h(
             
                  <el-tooltip class="item" effect="light" content="再次执行" placement="top-start">
               <span style=" cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                let tigger = false;
                this.$confirm(
                  "确认要再次执行【"+row.TaskNo+"】吗？",
                  "警告",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    center: true,
                  }
                ).then(() => {
                  if (tigger) return;
                  tigger = true;
                  row.Status=5;//重做
                  this.request('taskExecuteAgain', row);

                });
              }}
               > <i class="el-icon-info">再次 </i></span>
                     
                </el-tooltip>,        
                 
              ),
               
                h(
             
                  <el-tooltip class="item" effect="light" content="显示异常" placement="top-start">
               <span style="color:#E6A23C; cursor:pointer;'margin-right':'8px';'border-bottom':'1px solid'"
               onClick={($e) => {
                this.$refs.gridHeader.openModel3(row, column, index);   
              }}
               > <i class="el-icon-warning">异常</i></span>
                     
                </el-tooltip>,        
                 
              ),
            
              ]);
            }

            }  
             
            }   
                
            

          }
        });

       //加载完毕后，执行
       this.$nextTick(() => { 
        let ordercode=this.$route.query.OrderCode;
        if(ordercode!=null&&ordercode!=undefined){
        this.searchFormFields.OrderCode=ordercode;
        setTimeout(() => {
          this.search();
          // 这里可以放置你想在延迟后执行的代码
        }, 500);
        }
      });
      this.pagination.sizes= [30, 60, 100, 120,200],
        this.pagination.size = 200;
        this.setFiexdSearchForm(true);//
    },
    //计算时间差
    calculateTimeDifference(startDate, endDate) {
      const difference = endDate.getTime() - startDate.getTime();
      const days = Math.floor(difference / (1000 * 60 * 60 * 24));
      const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
      const remainingSeconds = Math.floor((difference % (1000 * 60)) / 1000);
      return hours + ":" + minutes + ":" + remainingSeconds;
   //   return { days, hours, minutes, seconds };
  },
    //秒转换为时分秒
     secondsToTime(seconds) {
      const hours = Math.floor(seconds / 3600).toString().padStart(2, '0');
      const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
      const remainingSeconds = (seconds % 60).toString().padStart(2, '0');
      
      return hours + ":" + minutes + ":" + remainingSeconds;
    },
    request(action, row) {
   //   let url = `api/V_PLAN_WORK_ORDER/${action}`;
   let url = `A_UpperComputer/${action}`;
      this.http.post(url, row, true).then((result) => {
        this.$message.success('执行成功');
        this.search();
      });
    },
    onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      this.height = window.innerHeight - 260;
    
    },
    test(){
      alert('test');
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
     
      //wheres: "[{\"name\":\"OrderCode\",\"value\":\"20250402-25-2062-0038\",\"displayType\":\"select\"}]"
    // 输出URL中的userId查询参数
  //   let ordercode=this.$route.query.OrderCode;
  //   if(ordercode!=null&&ordercode!=undefined){
  //     let wheres = [
  //   {
  //       'name': 'OrderCode',
  //       'value': ordercode, //多选查询值是逗号隔开
  //       'displayType': 'select'
  //   }]
  //    param.wheres.push(wheres);
  // }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true;
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true;
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    modelOpenAfter(row) {
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
    }
  }
};
export default extension;
